package Java_Concurrency_in_Practice.c6_3_1;

import java.util.List;
import java.util.concurrent.*;

public class Render {
    private final ExecutorService executor;

    public Render(ExecutorService executor) {
        this.executor = executor;
    }

    void renderPage(CharSequence source) {
        List<ImageInfo> imageInfos = RenderUtil.scanForImageInfo(source);
        CompletionService<ImageData> completionService = new ExecutorCompletionService<ImageData>(executor);
        for (final ImageInfo info : imageInfos) {
            completionService.submit(new Callable<ImageData>() {
                @Override
                public ImageData call() throws Exception {
                    return info.downloadImage();
                }
            });
        }

        RenderUtil.renderText(source);

        int n = imageInfos.size();
        for (int t = 0; t < n; t++) {
            try {
                Future<ImageData> f = completionService.take();
                ImageData imageData = f.get();
                RenderUtil.renderImage(imageData);
            } catch (InterruptedException e) {
               Thread.currentThread().interrupt();
            } catch (ExecutionException ee) {
                ee.printStackTrace();
            }
        }

    }
}
